<template>
  <div :class="{ show: show }" class="header-search">
    <el-button class="new-style" type="text" style="cursor: default;">当前租户：</el-button>
    <el-button type="text" @click="fetchTenantData()"
    >{{ selectedTenantName }}
    </el-button>
    <el-button class="new-style" style="margin-left: 20px; cursor: default;" type="text">
      当前用户：{{ selectUser }}
    </el-button>

    <el-dialog
      class="tenant-dialog"
      width="65%"
      title="租户信息"
      :visible.sync="dialogTableVisible"
    >
      <div class="tenant-info">
        <!-- <div class="tenant-operate">
          <span class="keyword">关键词：</span>
          <el-input placeholder="请输入租户名、集群" style="width: 20%;" clearable v-model="searchKeyword" @input="handleSearch">
          </el-input>
        </div> -->
        <div class="tenant-table">
          <el-table
            tooltip-effect="dark"
            align="center"
            style="width: 100%; margin: -10px"
            :data="tableData"
          >
            <el-table-column label="" width="45">
              <template slot-scope="scope">
                <el-radio
                  v-model="tenantId"
                  :value="scope.row.id"
                  :disabled="scope.row.disabled"
                  @change="handleRadioChange(scope.row)"
                ></el-radio>
              </template>
            </el-table-column>
            <el-table-column prop="tenantName" label="租户名">
            </el-table-column>
            <el-table-column prop="clusterZhname" label="集群">
            </el-table-column>
            <el-table-column prop="tenantName" label="命名空间">
            </el-table-column>
            <el-table-column prop="tenantDescription" label="描述">
            </el-table-column>
            <el-table-column prop="updateTime" label="创建时间">
            </el-table-column>
          </el-table>
        </div>
        <div style="float: right">
          <el-Pagination
            background
            layout="total, prev, pager, next, jumper"
            :page-size="tenantPagination.pageSize"
            :total="tenantPagination.total"
            :current-page.sync="tenantPagination.pageNum"
            @current-change="handleTenantPageChange"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {getTenantId, setTenantId} from "@/utils/tenantId";

  export default {
    name: "HeaderSearch",
    data() {
      return {
        //是否显示弹窗
        dialogTableVisible: false,
        //租户列表数据
        tableData: [],
        //当前选择租户的ID
        tenantId: "",
        //当前选择租户名称
        selectedTenantName: "",
        //租户分页信息
        tenantPagination: {
          total: 0,
          pageNum: 1,
          pageSize: 10,
        },
        show: true,
        searchKeyword: "",
      };
    },
    computed: {
      selectUser() {
        return this.$store.state.user.name
      }
    },
    async created() {
      if (getTenantId() == null || getTenantId() === "") {
        await this.$tenantManageApi
          .pageGetTenantInfo({
            pageSize: this.tenantPagination.pageSize,
            pageNum: this.tenantPagination.pageNum,
          })
          .then((response) => {
            //设置当前选择的租户ID
            this.tenantId = response.data.records[0].id;
            //设置当前选择的租户名称
            this.selectedTenantName = response.data.records[0].tenantName;
            //设置Cookie里面的tenantId
            setTenantId(this.tenantId);
          })
          .catch((error) => {
            console.error(error);
          });
      } else {
        this.$tenantManageApi
          .getTenantNameById(getTenantId())
          .then((response) => {
            //设置当前选择的租户ID
            this.tenantId = getTenantId();
            //设置当前选择的租户名称
            this.selectedTenantName = response.data;
          })
          .catch((error) => {
            console.error(error);
          });
      }
    },
    methods: {
      handleRadioChange(row) {
        this.handleCurrentChange(row);
      },
      //处理租户切换事件
      handleCurrentChange(val) {
        this.tenantId = val.id;
        this.selectedTenantName = val.tenantName;
        setTenantId(this.tenantId);
        this.dialogTableVisible = false;
        this.$notify({
          title: "成功",
          message: "租户切换成功！",
          type: "success",
        });
        // this.$router.push("/");
        setTimeout(() => {
          window.location.href = "/";
        }, 1000)
      },

      // 新添加函数
      // 搜索功能函数
      handleSearch() {
        this.tenantPagination.pageNum = 1; // 搜索时重置页码
        this.fetchTenantData();
      },
      handleTenantPageChange(pageNum) {
        this.tenantPagination.pageNum = pageNum;
        this.fetchTenantData();
      },

      // 分页获取租户数据
      fetchTenantData() {
        this.$tenantManageApi
          .pageGetTenantInfo({
            filterKey: this.searchKeyword,
            pageSize: this.tenantPagination.pageSize,
            pageNum: this.tenantPagination.pageNum,
          })
          .then((response) => {
            this.tableData = response.data.records;
            this.tenantPagination.total = response.data.total;
            this.tenantPagination.pageSize = response.data.size;

            // 查找当前租户并设置其为选中状态，禁用
            this.tableData.forEach((row) => {
              if (row.id === this.tenantId) {
                row.disabled = true; // 选择框禁用
                this.$nextTick(() => {
                  const radio = document.querySelector(`[value="${row.id}"]`);
                  if (radio) {
                    radio.checked = true;
                  }
                });
              } else {
                row.disabled = false;
              }
            });

            this.dialogTableVisible = true;
          })
          .catch((error) => {
            console.error(error);
          });
      },
    },
  };
</script>

<style lang="scss" scoped>
  .new-style {
    color: #1a1c1d;
  }

  .header-search {
    font-size: 0 !important;

    .search-icon {
      cursor: pointer;
      font-size: 18px;
      vertical-align: middle;
    }

    .header-search-select {
      font-size: 18px;
      transition: width 0.2s;
      width: 0;
      overflow: hidden;
      background: transparent;
      border-radius: 0;
      display: inline-block;
      vertical-align: middle;

      ::v-deep .el-input__inner {
        border-radius: 0;
        border: 0;
        padding-left: 0;
        padding-right: 0;
        box-shadow: none !important;
        border-bottom: 1px solid #d9d9d9;
        vertical-align: middle;
      }
    }

    &.show {
      .header-search-select {
        width: 210px;
        margin-left: 10px;
      }
    }
  }

  .tenant-info {
    margin-top: -10px;
  }

  .tenant-operate {
    background-color: #f9fbfd;
    padding: 10px 0;
  }

  .tenant-info {
    overflow-y: auto;
  }

  ::v-deep .el-checkbox__inner {
    display: none;
  }

  ::v-deep .el-dialog__body {
    padding: 0 20px;
  }

  ::v-deep .el-pagination {
    padding: 25px 5px 0;
  }
</style>
